<?php

namespace app\modules\api\controllers;

use app\models\ApiException;
use app\models\ApiVersion;
use app\models\KeyMap;
use Yii;
use yii\web\Response;

/**
 * 对外公开的接口
 * Class PublicController
 * @package app\modules\api\controllers
 */
class PublicController extends BasePublicController
{
    /**
     * 返回异常
     * @return array
     */
    public function actionError()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $exception = Yii::$app->errorHandler->exception;
        if ($exception === null) {
            return [
                'error' => 'SERVER',
                'message' => '未知错误。',
            ];
        }
        if (!($exception instanceof ApiException)) {
            return [
                'error' => 'SERVER',
                'message' => $exception->getMessage(),
            ];
        }
        /** @var ApiException $exception */
        return $exception->getErrorAsJson();
    }

    /**
     * 服务器时间戳
     * 输入
     * {}
     * 输出
     * {
     *     timestamp
     * }
     */
    public function actionServerTime()
    {
        return [
            'timestamp' => time(),
        ];
    }

    /**
     * 服务器版本
     * 输入
     * {}
     * 输出
     * {
     *     version,
     *     update_info
     * }
     * @throws ApiException
     */
    public function actionVersion()
    {
        /** @var ApiVersion $version */
        $version = ApiVersion::find()->orderBy('create_time DESC')->one();
        if (empty($version)) {
            throw new ApiException('SERVER', '系统没有定义版本号信息。');
        }
        return [
            'version' => $version->version,
            'update_info' => $version->update_info,
        ];
    }

    /**
     * 获取字典
     * 输入
     * {
     *     type
     * }
     * 输出
     * {
     *     key_map: [
     *         {t, k, v},
     *         ...
     *     ]
     * }
     * @throws ApiException
     */
    public function actionKeyMap()
    {
        $type = $this->json('type');
        $query = KeyMap::find();
        if (!empty($type)) {
            $query->andWhere(['t' => $type]);
        }
        $query->orderBy('t');
        $key_map = [];
        foreach ($query->each() as $key) {
            $key_map[] = [
                't' => $key->t,
                'k' => $key->k,
                'v' => $key->v,
            ];
        }
        return [
            'key_map' => $key_map
        ];
    }
}
